package com.bree.erp.jsf.view;

import java.io.Serializable;
import java.util.HashMap;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;

import org.apache.log4j.Logger;

import com.bree.erp.entity.PoItem;
import com.bree.erp.entity.PurchaseOrder;
import com.bree.erp.entity.Status;
import com.bree.erp.jsf.httpsess.SessionDataKey;
import com.bree.erp.jsf.httpsess.UserSessionData;
import com.bree.erp.service.InventoryFlowService;
import com.bree.erp.service.PoItemService;
import com.bree.erp.service.PurchaseOrderService;

@ManagedBean(name="dtInventoryWithdrawalView")
@ViewScoped
public class InventoryWithdrawalView implements Serializable {

	private static final long serialVersionUID = 1L;
	
	private static Logger LOG = Logger.getLogger(InventoryWithdrawalView.class);
	
	@ManagedProperty(value="#{userSession}")
	private UserSessionData userSession;
	
	@EJB
	private PurchaseOrderService poService;

	@EJB
	private PoItemService poItemService;
	
	@EJB
	private InventoryFlowService ifService;
	
	private PurchaseOrder purchaseOrder;
	
	@PostConstruct
	public void init() {
		
		Long id = userSession.get(SessionDataKey.SELECTED_PURCHASE_ORDER_ID, Long.class);
		LOG.debug("SELECTED_PURCHASE_ORDER_ID: " + id);
		if(id != null) {
			purchaseOrder = poService.read(id, true);
			
	
		}
	}
	public String withdraw() {

		String userId = userSession.getLoggedInUser().getEmail();
		
		if(purchaseOrder == null) {
			LOG.error("PuchaseOrder is NULL!");
			return null;
		}
		
		if(purchaseOrder.getItems() == null) {
			LOG.error("PuchaseOrder items is NULL!");
			return null;
		}
		
		poService.update(purchaseOrder.getId(), Status.WITHDRAW, userId);
		
		return "/inv/pickup";
	}
	/**
	 * @return the userSession
	 */
	public UserSessionData getUserSession() {
		return userSession;
	}
	/**
	 * @param userSession the userSession to set
	 */
	public void setUserSession(UserSessionData userSession) {
		this.userSession = userSession;
	}
	/**
	 * @return the purchaseOrder
	 */
	public PurchaseOrder getPurchaseOrder() {
		return purchaseOrder;
	}

}
